Strategy Method
It defines a family of algorithms, encapsulates each algorithm, and makes them interchangeable. This pattern allows the algorithm to vary independently from clients that use it. The Strategy pattern is particularly useful when you have multiple ways to perform a specific task, and you want to select one of those algorithms at runtime.
Structure
- Context: The class that uses a strategy. It maintains a reference to a
Strategyobject and can change it at runtime. - Strategy Interface: An interface that defines the method(s) that all concrete strategies will implement.
- Concrete Strategies: Classes that implement the
Strategyinterface, providing specific implementations of the algorithm.
Example
// Strategy Interface
interface SortingStrategy {
void sort(int[] numbers); // Method to sort the array
}
// Concrete Strategy for Bubble Sort
class BubbleSort implements SortingStrategy {
@Override
public void sort(int[] numbers) {
System.out.println("Sorting using Bubble Sort");
for (int i = 0; i < numbers.length - 1; i++) {
for (int j = 0; j < numbers.length - i - 1; j++) {
if (numbers[j] > numbers[j + 1]) {
// Swap numbers[j] and numbers[j + 1]
int temp = numbers[j];
numbers[j] = numbers[j + 1];
numbers[j + 1] = temp;
}
}
}
}
}
// Concrete Strategy for Quick Sort
class QuickSort implements SortingStrategy {
@Override
public void sort(int[] numbers) {
System.out.println("Sorting using Quick Sort");
quickSort(numbers, 0, numbers.length - 1);
}
private void quickSort(int[] numbers, int low, int high) {
if (low < high) {
int pi = partition(numbers, low, high);
quickSort(numbers, low, pi - 1);
quickSort(numbers, pi + 1, high);
}
}
private int partition(int[] numbers, int low, int high) {
int pivot = numbers[high]; // last element as pivot
int i = (low - 1); // index of smaller element
for (int j = low; j < high; j++) {
if (numbers[j] < pivot) {
i++;
// Swap numbers[i] and numbers[j]
int temp = numbers[i];
numbers[i] = numbers[j];
numbers[j] = temp;
}
}
// Swap numbers[i + 1] and numbers[high] (or pivot)
int temp = numbers[i + 1];
numbers[i + 1] = numbers[high];
numbers[high] = temp;
return i + 1;
}
}
// Context Class
class Sorter {
private SortingStrategy strategy; // Reference to a strategy
public void setStrategy(SortingStrategy strategy) {
this.strategy = strategy; // Set the sorting strategy
}
public void sort(int[] numbers) {
if (strategy != null) {
strategy.sort(numbers); // Delegate the sorting to the strategy
}
}
}
// Client code
public class Main {
public static void main(String[] args) {
Sorter sorter = new Sorter();
int[] numbers = {5, 3, 8, 1, 2};
// Set BubbleSort strategy
sorter.setStrategy(new BubbleSort());
sorter.sort(numbers); // Sort using Bubble Sort
// Set QuickSort strategy
sorter.setStrategy(new QuickSort());
sorter.sort(numbers); // Sort using Quick Sort
}
}